
package proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 */
public class MyHandler implements InvocationHandler {

    private Owner owner;

    public MyHandler(Owner owner) {
        super();
        this.owner = owner;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("黑中介租房子!");
        return method.invoke(owner, args);
    }

    public interface Owner {
        public boolean hire();
    }

    public static class HouseOwner implements Owner {
        public boolean hire() {
            System.out.println("hire house!");
            return false;
        }
    }

    public static void main(String[] args) {
        HouseOwner houseOwner = new HouseOwner();
        MyHandler myHandler = new MyHandler(new HouseOwner());
        Class<? extends HouseOwner> hClass = houseOwner.getClass();

        Owner j = (Owner) Proxy.newProxyInstance(hClass.getClassLoader(), hClass.getInterfaces(),
                myHandler);
        System.out.println(j.hire());

    }
}
